<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var arr = function (root) {
      let res = 0;
      function dfs(node = root) {
        if (node === null) return [0, 0];
        let [ls, lc] = dfs(node.left);
        let [rs, rc] = dfs(node.right);
        let ave = Math.floor((ls + rs + node.val) / (lc + rc + 1));
        if (ave === node.val) res += 1;
        return [ls + rs + node.val, lc + rc + 1]; // [sum, count]
      }
      dfs();
      return res;
    };
    console.log(arr(root = [4, 8, 5, 0, 1, null, 6]));
  </script>
</body>

</html>